package com.windchime.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Type;
import com.windchime.blog.entity.vo.TypeSearch;
import com.windchime.blog.mapper.TypeMapper;
import com.windchime.blog.service.TypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author WindChime
 * @since 2021-08-01
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    /**
     * 保存分类
     * @param type 分类
     * @return true
     */
    @Override
    public boolean saveType(Type type) {
        QueryWrapper<Type> wrapper = new QueryWrapper<>();
        wrapper.eq("name", type.getName());
        Type has_type = baseMapper.selectOne(wrapper);
        if (has_type == null) {
            return baseMapper.insert(type) > 0;
        }
        return false;
    }

    /**
     * 分页查询带条件
     * @param page       当前页
     * @param limit      当前页条目数量
     * @param typeSearch 条件
     * @return types
     */
    @Override
    public PageInfo<Type> selectTypeList(Integer page, Integer limit, TypeSearch typeSearch) {
        PageHelper.startPage(page, limit);
        QueryWrapper<Type> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (!StringUtils.isEmpty(typeSearch.getName())) {
            wrapper.like("name", typeSearch.getName());
        }
        List<Type> typeList = baseMapper.selectList(wrapper);
        return new PageInfo<>(typeList);
    }

    /**
     * 修改分类
     * @param type 分类
     * @return true
     */
    @Override
    public boolean editType(Type type) {
        QueryWrapper<Type> wrapper = new QueryWrapper<>();

        wrapper.notIn("id", type.getId());
        List<Type> tags = baseMapper.selectList(wrapper);
        List<String> typeNames = tags.stream().map(Type::getName).collect(Collectors.toList());

        if (!typeNames.contains(type.getName())) {
            return baseMapper.updateById(type) > 0;
        }

        return false;
    }
}
